package com.map
{
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;

	public class LoadMapCase
	{
		private var loadersArr:Array = [];
		private var mapDataManager:MapDatas;
		private var waitArr:Array = [];
		
		public function LoadMapCase()
		{
			mapDataManager = MapDatas.getInstance();
			createLoaders();
		}
		
		private function createLoaders():void {
			for(var i:int = 0; i < 10; i++) {
				var loader:MapLoader = new MapLoader;
				loadersArr.push(loader);
			}
		}
		
		public function startLoad(row:int, col:int, offsetx:int, offsety:int, container:Sprite):void {
			var url:String = MapDatas.common_path + row + "_" + col + ".jpg";
			var mapInfo:MapImgVO = new MapImgVO(url, row, col, container);
			mapDataManager.mapImgArr[MapDatas.COL_NUM * row + col] = mapInfo;
			load(url);
		}
		
		public static function getInstance():LoadMapCase {
			return _instance ||= new LoadMapCase;
		}
		
		private static var _instance:LoadMapCase;
		
		private function load(url:String):void {
			var loader:MapLoader = findLoader();
			if(loader) {
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
				loader.url = url;
				loader.load(new URLRequest(url));
			} else {
				waitArr.push(url);
			}
		}
		
		private function findLoader():MapLoader {
			var hasEmpty:Boolean = false;
			for each(var loader:MapLoader in loadersArr) {
				if(loader.state == MapLoader.EMPT) {
					hasEmpty = true;
					loader.state = MapLoader.BUSY;
					return loader;
				}
			}
			return null;
		}
		
		private var counter:int = 0;
		private function loadComplete(e:Event):void {
			var img:Bitmap = e.currentTarget.content as Bitmap;
			var loader:MapLoader = e.currentTarget.loader as MapLoader;
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loadComplete);
			loader.state = MapLoader.EMPT;
			var urlInfo:Array = loader.url.replace(MapDatas.common_path, "").match(/\d+/g);
			var row:int = int(urlInfo[0]);
			var col:int = int(urlInfo[1]);
			var mapInfo:MapImgVO = mapDataManager.mapImgArr[MapDatas.COL_NUM * row + col];
			if(mapInfo) {
				mapInfo.updateMapInfo(img);
			}
			counter ++;
			if(counter == MapDatas.COL_NUM * MapDatas.ROW_NUM) {
				trace("All map slice has loaded!");
			} else if(waitArr.length > 0){
				var url:String = waitArr.pop();
				load(url);
			}
		}
	}
}